package mapper;

import db.Room;
import mysql.JDBCUtil;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;

/**
 * @author 计算机系 ITAEM 摆渡人
 * @description
 * @date 2022/9/21 13:38
 */
public class RoomMapper extends JDBCUtil {

    public void insert(String roomId,String createUser){
        String insertSql = "INSERT INTO room VALUES(NULL,?,?,null)";
        PreparedStatement statement = getStatement(insertSql);
        try {
            statement.setObject(1,roomId);
            statement.setObject(2,createUser);
            statement.executeUpdate();
        } catch (SQLException sqlException){
            System.out.println("服务器错误--创建房间错误");
            sqlException.printStackTrace();
        } finally {
            closeAll();
        }
    }

    public Room selectByRoomId(String roomId){
        String selectSQL = "SELECT * FROM room WHERE room_id = ?";
        PreparedStatement statement = getStatement(selectSQL);
        try {
            statement.setObject(1,roomId);
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()){
                Room room = new Room();
                room.setId(resultSet.getInt("id"));
                room.setRoomId(resultSet.getString("room_id"));
                room.setCreateUser(resultSet.getString("create_user"));
                room.setJoinUser(resultSet.getString("join_user"));
                return room;
            } else {
                return null;
            }
        } catch (SQLException sqlException){
            System.out.println("服务器异常--selectByRoomId");
            sqlException.printStackTrace();
            return null;
        } finally {
            closeAll();
        }
    }

    public boolean deleteByRoomId(String roomId){
        String deleteSQL = "DELETE FROM room WHERE room_id = ?";
        PreparedStatement statement = getStatement(deleteSQL);
        try {
            statement.setObject(1,roomId);
            return statement.execute();
        } catch (SQLException sqlException){
            System.out.println("服务器错误--deleteByRoomId");
            sqlException.printStackTrace();
            return false;
        } finally {
            closeAll();
        }
    }

    public boolean deleteByUsername(String username){
        String deleteSQL = "DELETE FROM room WHERE create_user = ?";
        PreparedStatement statement = getStatement(deleteSQL);
        try {
            statement.setObject(1,username);
            return statement.execute();
        } catch (SQLException sqlException){
            System.out.println("服务器错误--deleteByUsername");
            sqlException.printStackTrace();
            return false;
        } finally {
            closeAll();
        }
    }
}
